package internal

import (
	"fmt"
	"github.com/name5566/leaf/gate"
	"github.com/name5566/leaf/log"
	"talent.com/agency_im/common/cxt"
	"talent.com/agency_im/common/msg"
	"talent.com/agency_im/common/pay"
	"talent.com/agency_im/common/platform"
	"talent.com/agency_im/common/user"
	"talent.com/agency_im/common/utils"
	"talent.com/agency_im/conf"
	"talent.com/agency_im/conf/g"
	"talent.com/server/durotar.git/tools/tz"
	"time"
)

func clearIdleAgents() {
	log.Debug("begin Clear idle agent ...")
	defer skeleton.AfterFunc(g.ClearIdleAgentsCycle, clearIdleAgents)

	ts := tz.GetNowTsMs()
	var (
		ag   gate.Agent
		uc   *cxt.UserContext
		ok   bool
		secs int64
	)
	g.AllAgents.Range(func(key, value interface{}) bool {
		ag, _ = value.(gate.Agent)
		uc, ok = ag.UserData().(*cxt.UserContext)
		if !ok {
			return true
		}
		secs = ts - uc.LastActiveAt
		if secs > g.UserMaxIdleSeconds*1000 {
			log.Debug("Remove Idle Agent %v", key)
			ag.Close()
			g.AllAgents.Delete(key)
			sendPresenceNT2Subscribers(uc.ID, msg.PRESENCE_TYPE_OFFLINE)
		}
		return true
	})
}

func expireSubscribers() {
	defer skeleton.AfterFunc(g.ExpireSubscribersCycle, expireSubscribers)

	for _, subs := range g.SubscribeUserMap {
		for sub, ttl := range subs {
			if tz.GetNowTs()-ttl >= g.ExpireSubscribeTTLSeconds {
				delete(subs, sub)
			}
		}
	}
}

func clearLeavingAgents() {
	log.Debug("begin check agent leaving ...")
	defer skeleton.AfterFunc(g.ClearLeavingCycle, clearLeavingAgents)
	var (
		u     *user.User
		err   error
		times uint64
	)
	skeleton.Go(func() {
		g.UserLeavingTimeMap.Range(func(key, value interface{}) bool {
			u, err = user.GetUser(key.(uint64))
			times = value.(uint64)
			if err != nil {
				return false
			}
			if u.LeavingTime <= uint64(tz.GetNowTs())-times {
				log.Debug("clearLeavingAgents find  agent left %v", u.ID)

				if ok, _ := pay.MakeAgencyOffWork(u.ID); ok {
					g.UserLeavingTimeMap.Delete(key.(uint64))
					m := &msg.Message{
						TopicType: int8(msg.TOPIC_TYPE_PRIVATE),
						SourceID:  conf.ServerConfig().Pay.PayOperatorID,
						TargetID:  u.ID,
						MsgType:   int8(msg.MSG_TYPE_TEXT),
						SendSelf:  false,
						Info: `<div class="operation-info" data-title="{暂离提醒}">
							   <p class="operation-info-title">暂离提醒</p>
                               <p style="font-size: 16px;color: #222">您当前已暂离，系统自动为您下班，请您注意及时回复用户消息。</p>
    						   </div>
                               `,
					}
					SendMessage(m)
				}
			}
			return true
		})
	}, func() {
	})
}

func unRepliedMsgWarning() {
	log.Debug("begin check unreply msg ...")
	warningTime := 5 * 60
	defer skeleton.AfterFunc(g.CheckUnRepliedCycle, unRepliedMsgWarning)
	skeleton.Go(func() {
		pageNo := 1
		pageSize := 30
		for {
			message := ""
			m, _ := time.ParseDuration("-1m")
			startUpdatedAt := time.Now().Add(30 * m)
			if _, topics, err := msg.ListTopics(0, conf.ServerConfig().Pay.AgencyPlatformID, []uint64{}, 0, startUpdatedAt, time.Time{}, 0, pageNo, pageSize); err != nil {
				return
			} else {
				if len(topics) == 0 {
					break
				}
				for _, t := range topics {
					m, _ := msg.GetOldestMessageBySourceID(t.UserID, t.TargetID)
					if m == nil || uint64(tz.GetNowTs())-uint64(m.CreatedAt.Unix()) > uint64(warningTime) {
						sourceUser, _ := user.GetUser(t.UserID)
						targetUser, _ := user.GetUser(t.TargetID)
						//times := uint64(tz.GetNowTs()) - uint64(m.CreatedAt.Unix())
						if targetUser.ID != conf.ServerConfig().Pay.PayOperatorID {
							targetPlatform, _ := platform.GetPlatformByID(targetUser.PlatformID)
							println(t.ID)
							message += fmt.Sprintf("%v(%v) 已超时未回复用户 %v 平台 %v 用户 \n", sourceUser.Nickname, sourceUser.ThirdUserID, targetPlatform.Name, targetUser.ThirdUserID)
						}
					}

				}
				if message != "" {
					utils.SendMsg(message, conf.ServerConfig().Pay.TelegramGroupID)
				}
				pageNo += 1
			}
		}
	}, func() {
	})
}
